 //! `commands` 插件的入口实现

use std::any::Any;
use std::sync::Arc;
use async_trait::async_trait;

use crate::core::manifest::ContributionKeywordDefinition;
use crate::core::plugin::RigPlugin;
use crate::core::services::context::ActivateContext;

use super::imp::CommandsImplement;


/// Commands 插件的结构体
pub struct CommandsPlugin {
    /// 插件持有的核心实现，并用 Arc<Mutex<...>> 保证线程安全和内部可变性
    service_context: Arc<CommandsImplement>,
}

impl CommandsPlugin {
    pub fn new() -> Self {
        Self {
            service_context: Arc::new(CommandsImplement::new()),
        }
    }
}

#[async_trait]
impl RigPlugin for CommandsPlugin {
    async fn activate(&mut self, _ctx: &ActivateContext) -> Option<Arc<dyn Any + Send + Sync>> {
        println!("Commands plugin activated.");
        None // Commands 插件自身不向外暴露 API
    }

    async fn deactivate(&mut self, _ctx: &ActivateContext) {
        println!("Commands plugin deactivated.");
    }

    /// 当内核需要 `commands` 关键字的实现时，调用此方法
    fn get_contribution_keyword(
        &self,
        _keyword: &ContributionKeywordDefinition,
        _ctx: &ActivateContext,
    ) -> Option<Box<dyn Any + Send + Sync>> {
        // 返回我们核心实现的克隆
        Some(Box::new(self.service_context.clone()))
    }

    /// 当其他插件依赖 `commands` 上下文时，内核调用此方法
    fn get_context(&self) -> Option<Arc<dyn Any + Send + Sync>> {
        // The `service_context` is already an `Arc`, so we just clone it.
        Some(self.service_context.clone() as Arc<dyn Any + Send + Sync>)
    }
}
